package cn.wk.interceptor;

import cn.wk.util.HttpUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
    private String TOKEN_NAME = "Authorization";
    @Value("${auth.client.tokenurl}")
    private String TOKEN_URL;
    @Value("${auth.client.clientid}")
    private String CLIENTID;
    @Value("${auth.client.secret}")
    private String SECRET;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //发送HTTP请求，用客户端模式获取token
        TOKEN_URL = String.format(TOKEN_URL, CLIENTID, SECRET);
        Map<String, String> map = HttpUtil.sendPost(TOKEN_URL);
        if(map!=null && null !=map.get("access_token")){
            //获取请求头中的token
            String access_token = "Bearer "+map.get("access_token");
            //再将token设置给feign的请求
            requestTemplate.header(TOKEN_NAME, access_token);
            System.out.println("--------走了拦截器----------");
            log.info(access_token);
        }else {
            System.out.println("--------------auth中的feign添加token失败-------------------------------------");
        }



    }
}
